import axios from 'axios'
import type { AxiosInstance, AxiosError, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { LocalStorage } from '@/utils/use-storage'

export interface Result<T> {
    code: number
    message: string
    success: boolean
    data: T
}

export interface RequestForm {
    [key: string]: any
}

const instance: AxiosInstance = axios.create({
    // baseURL: 'http://localhost:3000',
    baseURL: 'http://localhost:5000',
    timeout: 10000,
    headers: { 'Content-Type': 'application/json' },
})

instance.interceptors.request.use(
    (config) => {
        const accessToken = LocalStorage.get('accessToken')
        if (accessToken) {
            config.headers.Authorization = `Bearer ${accessToken}`
        }
        // if(config.data) {}
        return config
    },
    (error) => {
        return Promise.reject(error)
    },
)

instance.interceptors.response.use(
    (response: AxiosResponse) => {
        const { code, message } = response.data
        if (code === 200) {
            return response.data
        } else {
            ElMessage.error(message)
            return Promise.reject(response.data)
        }
    },
    (error: AxiosError) => {
        if (error.message.includes('timeout')) {
            ElMessage.error('请求超时')
        }
        const status = error.response?.status
        let message = error.message || ''
        switch(status) {
            case 401:
                message = '认证失效'
                break
            case 404:
                message = '请求地址出错'
                break
            case 500:
                message = '服务器故障'
                break
        }

        ElMessage.error(error.message)

        // if(error.message) {
        //     ElMessage.error(error.message)
        // }
        
        return Promise.reject(error)
    },
)

export const get = <R = any>(
    url: string,
    params?: RequestForm,
): Promise<Result<R>> => {
    return instance.get(url, { params })
}

export const post = <R = any>(
    url: string,
    data?: RequestForm,
): Promise<Result<R>> => {
    return instance.post(url, data)
}
